package com.saifan.wyy_ov.ui.onlishop;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.alipay.AlipayResult;
import com.saifan.alipay.AlipayUtils;
import com.saifan.wxpay.WXPayUtils;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.common.BaseActivity;
import com.saifan.wyy_ov.data.bean.MyOrderBean;
import com.saifan.wyy_ov.data.bean.PayResultBean;
import com.saifan.wyy_ov.data.bean.SubmitOrderBean;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;

import com.saifan.wyy_ov.ui.view.MaterialDialog;
import com.saifan.wyy_ov.utils.ActivitysManager;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.DialogUtil;
import com.saifan.wyy_ov.utils.PriceUtils;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;
import com.saifan.wyy_ov.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import net.sourceforge.simcpux.Constants;

import java.util.ArrayList;
import java.util.List;

public class PayActivity extends BaseActivity {
    // Content View Elements

    private TextView tv_total;
    private RadioButton cb_pay;
    private RadioButton cb_weixin;
    private RadioButton cb_ali;
    private RadioGroup payWay;
    private ListView listView;
    List<SubmitOrderBean> list;
    int paymentWay;
    double total;
    String order_number;
    //从购物车传来的数据
    String submitOrderBeanjson;
    private Button pay_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        paymentWay = getIntent().getIntExtra("paymentWay", 0);
        total = getIntent().getDoubleExtra("total", 0.0f);
        submitOrderBeanjson = getIntent().getStringExtra("SubmitOrderBeans");
        setContentView(R.layout.activity_pay);
        bindViews();
        setEnabledNavigation(true);
    }

    private void bindViews() {


        pay_button = (Button) findViewById(R.id.pay_button);
        tv_total = (TextView) findViewById(R.id.tv_total);
        cb_pay = (RadioButton) findViewById(R.id.cb_pay);
        cb_weixin = (RadioButton) findViewById(R.id.cb_weixinpay);
        cb_ali = (RadioButton) findViewById(R.id.cb_alipay);
        payWay = (RadioGroup) findViewById(R.id.pay_way);
        listView = (ListView) findViewById(R.id.listview);
        list = new Gson().fromJson(submitOrderBeanjson, new TypeToken<List<SubmitOrderBean>>() {
        }.getType());
        CommonAdapter<SubmitOrderBean> adapter = new CommonAdapter<SubmitOrderBean>(this, list, R.layout.pay_order_list_item) {
            @Override
            public void convert(ViewHolderHelper helper, SubmitOrderBean item) {
                // TODO Auto-generated method stub
                helper.setText(R.id.tv_number, item.getOrderNumber() + "");
                helper.setText(R.id.tv_amount, item.getAmount() + " 元");
            }
        };
        listView.setAdapter(adapter);
        tv_total.setText(PriceUtils.getPrice(total) + "元");


    }

    public void pay(final View view) {
        view.setEnabled(false);
//		AlipayUtils alipayUtils = new AlipayUtils();
//		alipayUtils.alipay(PayActivity.this);


//		WXPayUtils wxPayUtils = new WXPayUtils();
//		wxPayUtils.sendPayReq(PayActivity.this, "wx20150909105926712e7042b70181127613");
        if (payWay.getCheckedRadioButtonId() == R.id.cb_weixinpay)//微信支付
            paymentWay = 0;
        else if (payWay.getCheckedRadioButtonId() == R.id.cb_alipay)//支付宝支付
            paymentWay = 1;
        else if (payWay.getCheckedRadioButtonId() == R.id.cb_pay) //货到付款
            paymentWay = 2;
        List<MyOrderBean> myOrderBeans = new ArrayList<MyOrderBean>();
        for (SubmitOrderBean submitOrderBean : list) {
            MyOrderBean myOrderBean = new MyOrderBean();
            myOrderBean.setPaymentWay(paymentWay);
            myOrderBean.setID(submitOrderBean.getID());
            myOrderBean.setOrderState(getRoomInfoBean().getXMBS());
            myOrderBeans.add(myOrderBean);
        }
        GetData getData = new GetData();
        getData.getDataJson(PayActivity.this, Api.GroupBuy.PAYMENT, myOrderBeans, "请稍候! ", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                // TODO Auto-generated method stub
                int result = -1;//0:成功，1，失败
                if (payWay.getCheckedRadioButtonId() == R.id.cb_pay) {
                    result = 0;
                    Intent intent = new Intent(PayActivity.this, WXPayEntryActivity.class);
                    intent.putExtra("pay_result", result);
                    startActivity(intent);
                    ActivitysManager.getManager().removeActivity(PayActivity.this);

                } else if (payWay.getCheckedRadioButtonId() == R.id.cb_weixinpay) {
                    List<PayResultBean> list = (new Gson()).fromJson(json, new TypeToken<List<PayResultBean>>() {
                    }.getType());
                    if (list != null) {
                        Constants.API_KEY = list.get(0).getKey();
                        Constants.APP_ID = list.get(0).getAPPID();
                        Constants.MCH_ID = list.get(0).getMCHID();
                        WXPayUtils wxPayUtils = new WXPayUtils();
                        if (!wxPayUtils.isWXAppInstalledAndSupported(PayActivity.this, WXAPIFactory.createWXAPI(PayActivity.this, null))) {
                   final MaterialDialog dialog= DialogUtil.createDailog(PayActivity.this,"提示","您尚未安装微信");
                            dialog.setNegativeButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                    dialog.dismiss();
                                }
                            });
                            dialog.show();
                            pay_button.setEnabled(true);
                            return;
                        }
                        wxPayUtils.sendPayReq(PayActivity.this, list.get(0).getPrepay_id());
//                        ActivitysManager.getManager().removeActivity(PayActivity.this);
                    } else {
                        pay_button.setEnabled(true);
                        ToastUtil.showToast(PayActivity.this, "服务器出错了 !");
                    }
                } else if (payWay.getCheckedRadioButtonId() == R.id.cb_alipay) {
                    List<PayResultBean> list = (new Gson()).fromJson(json, new TypeToken<List<PayResultBean>>() {
                    }.getType());
                    if (list != null) {
                        AlipayUtils alipayUtils = new AlipayUtils();
                        alipayUtils.alipay(PayActivity.this, list.get(0).getPrepay_id(), new AlipayResult() {
                            @Override
                            public void onResult(int code) {
                                Intent intent = new Intent(PayActivity.this, WXPayEntryActivity.class);
                                intent.putExtra("pay_result", code);
                                startActivity(intent);
                                ActivitysManager.getManager().removeActivity(PayActivity.this);
                            }
                        });
                    } else {
                        pay_button.setEnabled(true);
                        showToast("服务器出错了 !");

                    }
                }
            }

            @Override
            public void onFailed(String str) {
                // TODO Auto-generated method stub
                pay_button.setEnabled(true);
                showToast("发生未知错误");

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
        }
        return super.onOptionsItemSelected(item);
    }


}
